package com.qingcheng.controller.goods;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.UploadService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lin.jia
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Reference
    private UploadService uploadService;

    /**
     * 本地上传图片
     *
     * @param file    文件对象
     * @param request 网络请求
     * @return 路径
     */
    @PostMapping("/native")
    public String nativeUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException { //获取session
        HttpSession session = request.getSession();
        //获取Servlet上下文
        ServletContext servletContext = session.getServletContext();
        //获取路径
        String img = servletContext.getRealPath("img");
        return uploadService.nativeUpload(file.getBytes(), img, file.getOriginalFilename());
    }

    /**
     * OSS上传图片
     *
     * @param file   文件对象
     * @param folder 前缀
     * @return 路径
     */
    @PostMapping("/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file, String folder) throws IOException {
        return uploadService.ossUpload(file.getBytes(), file.getOriginalFilename(), folder);
    }
}
